package com.z6school.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.z6school.manage.common.annotation.RequiredLog;
import com.z6school.manage.common.pojo.PageObject;
import com.z6school.manage.mapper.TeacherMapper;
import com.z6school.manage.mapper.UserMapper;
import com.z6school.manage.po.Teacher;
import com.z6school.manage.po.User;
import com.z6school.manage.service.TeacherService;
import com.z6school.manage.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private UserService userService;
    /**查询所有教师信息*/
    @Override
    @RequiredLog(operation = "查询教师信息")
    @RequiresPermissions("sys:teacher:view")
    public PageObject<Teacher> findAllMessage(
            String username, Integer pageCurrent) {
        //1.参数校验
        if(pageCurrent == null || pageCurrent<1)
            throw new IllegalArgumentException("页码值不正确");
        //2.PageHelper
        Page<Object> page = PageHelper.startPage(pageCurrent, 5);
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        List<Teacher> teacherList;
        if (username==null){
            teacherList = teacherMapper.selectList(null);
        }else {
            queryWrapper.like("name", username);
            teacherList = teacherMapper.selectList(queryWrapper);
        }
        //3.封装结果
        return new PageObject<Teacher>( page.getTotal(), teacherList, (long) page.getPages(), 5, pageCurrent);
    }


    @Override
    @RequiredLog(operation = "添加教师信息")
    @RequiresPermissions("sys:teacher:edit")
    public void addTeacherMessage(Teacher teacher) {
        Integer num = (int) ((Math.random() * 9 + 1) * 100000);
        teacher.setNumber(num.toString());
        User user = new User();
        user.setUsername(teacher.getNumber()).setPassword("123456").setMobile(teacher.getPhone()).setRole("2");
        Integer[] roleIds = new Integer[]{2};
        userService.saveObject(user, roleIds);
        teacherMapper.insert(teacher);
    }

    @Override
    @RequiredLog(operation = "删除教师信息")
    @RequiresPermissions("sys:teacher:delete")
    public void doDeleteObjects(String ids) {
        String[] split = ids.split(",");
        List<String> arrayList = new ArrayList<String>();
        for (int i=0;i<split.length;i++){
            arrayList.add(split[i]);
        }
        teacherMapper.deleteBatchIds(arrayList);
    }
}
